package com.appjishu.web.util.pubsub;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import com.appjishu.web.util.pubsub.model.MqMessage;

/**
 * @author edmond
 * @date 2020/03/25
 */
@Component
public class EventProcessor extends MessageListenerAdapter implements ApplicationContextAware {
    private ApplicationContext context;
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String msg = redisTemplate.getStringSerializer().deserialize(body);
        String topic = redisTemplate.getStringSerializer().deserialize(channel);
        context.getBeansOfType(EventConsumer.class).forEach((bean, consumer) -> {
            if(topic.equals(PubSubConfig.pubsubPrefix + consumer.topic())) {
                consumer.doHander(new MqMessage(msg));
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

}
